#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
玩家对话模板系统
用于格式化和结构化玩家与NPC的对话内容
"""

from typing import Any, Dict


class UserDialogueTemplate:
    """游戏角色对话模板类"""

    # 基础对话模板
    BASE_TEMPLATE = """
玩家说：{user_input}

# 当前场景
{scene_description}

# {character_name}当前状态
{character_status}

# 短期记忆
{short_memory}

请你以{character_name}的身份、性格、记忆状态进行回应{response_guidance}
{character_name}说：
"""

    # 场景描述模板组件
    SCENE_COMPONENTS = {
        "location": "你身处 {location}。",
        "description": "{scene_description}",
        "atmosphere": "环境：{atmosphere}",
        "time": "时间：{time_context}",
        "weather": "天气：{weather}",
        "background_event": "背景事件：{background_event}",
    }

    # 状态描述模板组件
    STATUS_COMPONENTS = {
        "emotion": "- 情绪：{emotion_state}",
        "relationship": "- 关系判断：{relationship_status}",
        "feeling": "- 当前感受：{feeling_description}",
        "value_judgment": "- 对玩家的价值观评价：{value_judgment}",
        "story_background": "- 背景故事：{story_background}",
        "awe_description": "- 敬畏感：{awe_description}",
        "mood": "- 心情：{mood_description}",
        "physical_state": "- 身体状态：{physical_state}",
        "mental_state": "- 心理状态：{mental_state}",
    }

    @classmethod
    def create_user_dialogue(cls, user_data: Dict[str, Any]) -> str:
        """
        创建格式化的玩家对话内容

        Args:
            user_data: 玩家对话数据字典，包含以下字段：
                - user_input: 玩家输入内容
                - character_name: 角色名称
                - scene_data: 场景数据字典
                - status_data: 状态数据字典
                - short_memory: 短期记忆列表或字符串
                - response_guidance: 回应指导语（可选）

        Returns:
            格式化的对话字符串
        """
        # 提取基本信息
        user_input = user_data.get("user_input", "")
        character_name = user_data.get("character_name", "角色")
        scene_data = user_data.get("scene_data", {})
        status_data = user_data.get("status_data", {})
        short_memory = user_data.get("short_memory", [])
        response_guidance = user_data.get("response_guidance", "")

        # 构建场景描述
        scene_description = cls._build_scene_description(scene_data)

        # 构建状态描述
        character_status = cls._build_status_description(status_data)

        # 处理短期记忆
        if isinstance(short_memory, list):
            memory_text = "\n".join([f"- {item}" for item in short_memory if item])
        else:
            memory_text = short_memory if short_memory else ""

        # 处理回应指导语
        if response_guidance and not response_guidance.startswith("，"):
            response_guidance = "，" + response_guidance

        # 生成完整对话
        dialogue = cls.BASE_TEMPLATE.format(
            user_input=user_input,
            scene_description=scene_description,
            character_status=character_status,
            character_name=character_name,
            short_memory=memory_text,
            response_guidance=response_guidance,
        )

        return dialogue.strip()

    @staticmethod
    def _build_scene_description(scene_data: Dict[str, Any]) -> str:
        """
        构建场景描述

        Args:
            scene_data: 场景数据字典

        Returns:
            格式化的场景描述字符串
        """
        scene_parts = []

        # 处理场景数据，只保留值，删除键
        if scene_data:
            for key, value in scene_data.items():
                if value and str(value).strip():
                    scene_parts.append(str(value))

        # 如果没有场景数据，使用默认信息
        if not scene_parts:
            scene_parts.append("当前场景信息不详。")

        return "\n".join(scene_parts)

    @staticmethod
    def _build_status_description(status_data: Dict[str, Any]) -> str:
        """
        构建状态描述

        Args:
            status_data: 状态数据字典

        Returns:
            格式化的状态描述字符串
        """
        status_parts = []

        # 处理状态数据，只保留值，删除键
        if status_data:
            for key, value in status_data.items():
                if value and str(value).strip():
                    status_parts.append(f"- {str(value)}")

        # 如果没有状态数据，使用默认信息
        if not status_parts:
            status_parts.append("当前状态信息不详。")

        return "\n".join(status_parts)


def get_user_template(user_data: Dict[str, Any]) -> str:
    """
    获取玩家对话模板

    Args:
        user_data: 玩家对话数据字典

    Returns:
        格式化的玩家对话字符串
    """
    return UserDialogueTemplate.create_user_dialogue(user_data)


def create_user_dialogue_params(dialogue_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    创建玩家对话参数字典

    Args:
        dialogue_data: 对话相关数据字典，包含：
            - user_input: 玩家输入
            - character_name: 角色名称
            - scene_info: 场景信息字典
            - status_info: 状态信息字典
            - memory_list: 记忆列表
            - guidance: 回应指导（可选）

    Returns:
        格式化的参数字典
    """
    return {
        "user_input": dialogue_data.get("user_input", ""),
        "character_name": dialogue_data.get("character_name", "角色"),
        "scene_data": dialogue_data.get("scene_info", {}),
        "status_data": dialogue_data.get("status_info", {}),
        "short_memory": dialogue_data.get("memory_list", []),
        "response_guidance": dialogue_data.get("guidance", ""),
    }
